import './style/index.css'
import { Icon, Button, Input, message, Modal} from 'antd'
import { WeaNewScroll, WeaTools, WeaLocaleProvider, WeaInputSearch} from 'ecCom'
import trim from 'lodash/trim'
import isEqual from 'lodash/isEqual';
import ForwadStore from './../../../../stores/forwardStore';
import UserPhraseEdit from './../../../wf-user-phrase-edit/index'
import UserPhraseEditStore from './../../../../stores/UserPhraseEdit'
import {toJS} from 'mobx'
const forwadStore = new ForwadStore();
const userPhraseEditStore = new UserPhraseEditStore();
const getLabel = WeaLocaleProvider.getLabel;
/**
 * 常用批示语
 */
export default class Main extends React.Component{
	constructor(props) {
		super(props);
		this.state = {
			isAdd:false,
			newphrase: '',
			searchValue:"",
			phraseInfo: this.props.phraseInfo || [],
			phraseInfo_back: this.props.phraseInfo || [],
			isShowAddDialog:false
		}
	}
	
	componentWillReceiveProps(nextProps){
		if(nextProps.visible != this.props.visible){
			this.setState({ isAdd: false, phraseInfo: toJS(nextProps.phraseInfo) || [], phraseInfo_back: toJS(nextProps.phraseInfo) || [], searchValue: "" });
		}
	}
	
	shouldComponentUpdate(nextProps, nextState) {
		return !isEqual(this.state.phraseInfo, nextState.phraseInfo)||
			   this.state.isAdd !== nextState.isAdd||
			   this.state.isShowAddDialog !== nextState.isShowAddDialog||
			   this.state.newphrase !== nextState.newphrase||
			   this.props.visible !== nextProps.visible||
			   this.props.signinputPhraseDirection !==nextProps.signinputPhraseDirection||
			   this.props.signinputPhraseOffset !==nextProps.signinputPhraseOffset||
			   this.props.triangleLeft !==nextProps.triangleLeft;
	}

	/**
	 * 控制显示和隐藏
	 */
	doChangeStatus = (params = {}) => {
		WeaTools.callApi('/api/workflow/userDefaultSetting/doChangeStatus', 'POST', params).then(res => {
			const { success = "", msg = "" } = res;
			msg && message.success(msg);
			if (success == 1) {
				let phraseInfo = this.state.phraseInfo.filter(item => item.id != params.id);
				this.setState({ phraseInfo });
				this.props.saveCallBack();
			}
		})
	}
	

	/**
	 * 删除 
	 */
	doDel = (params = {}) => {
		WeaTools.callApi('/api/workflow/userDefaultSetting/doDel', 'POST', params).then(res => {
			res.msg && message.success(res.msg);
			if (res.success == 1) {
				let phraseInfo = this.state.phraseInfo.filter(item => item.id != params.ids);
				this.setState({ phraseInfo });
				this.props.saveCallBack();
			}
		})
	}

	render(){
		const commentsLabel = getLabel(528468, "批示语吗？")
		let {visible ,extendParams = {},setVisiable,signinputPhraseDirection,use_textarea_signinput} = this.props;
		const {phraseInfo=[],isAdd,newphrase} = this.state;
		const addBtn = (<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@0etze5`} onClick={this.doAddPhrase}>{getLabel(826,'确定')}</Button>);
		const contentStyle = {
			display:visible?'block':'none'
		}
		if(isAdd) contentStyle[`border-bottom`] = 0;
		let {signinputPhraseWidth,signinputPhraseHeight = 95} = extendParams;
		signinputPhraseHeight = phraseInfo.length >= 5 ? 230 : phraseInfo.length * 30 + 80;
		const { signinputPhraseOffset }=this.props;
		if(signinputPhraseWidth) {
			contentStyle['width'] = `${signinputPhraseWidth}px`;
            contentStyle['left'] = `${signinputPhraseOffset -1}px`;
        }
		const{ triangleLeft }=this.props;
		let footInputStyle = {};
		if(signinputPhraseWidth > 251) footInputStyle['width'] = '100%';
		if(signinputPhraseDirection === 'bottom') {
            contentStyle['marginTop'] = '11px';
		} else {
            contentStyle['marginTop'] = `${-signinputPhraseHeight - 40}px`;
		}
		const _this = this;
		return (
			<div className="wf-ckeditor-wfphrase" ref="wfphrase">
				<div className={`wea-cb-item`} onClick={(e)=>{
					this.props.showComponent(visible ? '':'WfPhrase')
						e.stopPropagation();
					}}>
					<span className={`wea-cbi-icon icon-coms-Advice`}/>
					<span className='wea-cbi-text'>{getLabel(22409,'常用批示语')}</span>
				</div>
				<div className="wfphrase-content" style={contentStyle}>
					{signinputPhraseDirection === 'bottom' && <div className="triangle_border_nw" style={{left : `${triangleLeft}px`}}></div>}
					<div className="wfphrase-search">
						<WeaInputSearch ecId={`${this && this.props && this.props.ecId || ''}_WeaInputSearch@aipizw`}
							value={this.state.searchValue}
							style={{ height: "28px",width:"100%"}}
							onChange={(val) => {
								this.setState({ searchValue: val })
								if (val) {
									let phraseInfo = this.state.phraseInfo_back.filter(item => (item.workflowPhrases.includes(val) || item.workflowPhrasesContent.includes(val)));
									this.setState({ phraseInfo });
								} else {
									this.setState({ phraseInfo: this.state.phraseInfo_back });
								}
							}}
						/>
					</div>
					<div className="wfphrase-list">
						{phraseInfo.length > 0 && 
							// <WeaNewScroll >
							<WeaNewScroll ecId={`${this && this.props && this.props.ecId || ''}_WeaNewScroll@84fknw`} >{/**height={signinputPhraseHeight} */}
								<ul>
								{
									phraseInfo.map(item => {
										if (item.status == 1) {
											return <li className="wfphrase-list-item" onClick={this.addPhrasesToCKEditor.bind(this, item)}>
												<span title={item.workflowPhrases}>{item.workflowPhrases != "" && <div className="wfphrase-list-content">{item.workflowPhrases}</div>}</span>
												<div className="wfphrase-list-edit">
													{item.right == 1 && <i className="icon-coms-delete wfphrase-edit-icon font14" title={getLabel(91, "删除")} onClick={(e) => {
														Modal.confirm({
															content: getLabel(84051, "确定要删除") + `"` + item.workflowPhrases + `"` + commentsLabel,
															onOk: () => {
																//传入id删除
																this.doDel({ ids: item.id });
																e.stopPropagation();
															}
														})
														e.stopPropagation();
													}} />}
													{item.right == 1 && <i className="icon-coms-edit wfphrase-edit-icon font14" title={getLabel(93, "编辑")} onClick={(e) => {
														e.stopPropagation();
														const { belongTest } = this.props;
														if(belongTest){
															Modal.warning({
																title:getLabel(131329,'信息确认'),
																content: getLabel(386161,"此操作暂不支持流程测试!"),
																okText: getLabel(83446,`确定`)
															});
														
															return;
														}
														this.props.showComponent("");
														userPhraseEditStore.onEdit(item.id);//让后端返出id，item.id
														_this.setState({ isShowAddDialog: true })
													}} />}
													<i className="icon-coms02-hide wfphrase-edit-icon font17" title={getLabel(16636, "隐藏")}
													 onClick={(e) => {
														Modal.confirm({
															content: getLabel(507407, "确定要隐藏") + `"` + item.workflowPhrases + `"` + commentsLabel,
															onOk: () => {
																this.doChangeStatus({ id: item.id, groupid: item.groupid, status: item.status });
																e.stopPropagation();
															}
														})
														   e.stopPropagation(); 
														}}
													  />
												</div>
											</li>
										}
									})
								}
								</ul>
							</WeaNewScroll>
						}
					</div>
					{!isAdd ? 
						<div className="wfphrase-foot-btn">
							<Icon ecId={`${this && this.props && this.props.ecId || ''}_Icon@2xarzp`} title={getLabel(507408,"添加批示语")} type="plus-circle-o" onClick={() => {
								const {editorId,belongTest} = this.props;
								if(belongTest){
									Modal.warning({
										title:getLabel(131329,'信息确认'),
										content: getLabel(386161,"此操作暂不支持流程测试!"),
										okText: getLabel(83446,`确定`)
									});
									return;
								}
								this.props.showComponent("");
								let defaultContent="";
								if(window.CK_REF[editorId] && window.CK_REF[editorId].getEditor && window.CK_REF[editorId].getEditor().getData){
									defaultContent = window.CK_REF[editorId].getEditor().getData();
								}
								userPhraseEditStore.onEdit("", defaultContent);
								_this.setState({ isShowAddDialog: true })
							}} />
						</div>
						:
						<div className="wfphrase-foot-input" style={footInputStyle}>
							<Input ecId={`${this && this.props && this.props.ecId || ''}_Input@s63dqv`} type="text" onChange={this.doChangeEvent} value={newphrase}/>
							<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@ex4p35`} onClick={this.doAddPhrase}>{getLabel(826,'确定')}</Button>
						</div>
					}
				</div>
				{this.state.isShowAddDialog&&<UserPhraseEdit 
					ecId={`${this && this.props && this.props.ecId || ''}_UserPhraseEdit@e8z6pp`}
					baseProps={{
						use_textarea_signinput,
					}}
					store={userPhraseEditStore}
					visiable = {this.state.isShowAddDialog}
					saveCallBack={(phraseInfo,replaceid) => {
						let _phraseInfo = this.state.phraseInfo||[];
						if(replaceid){
							for(let i=0;i<_phraseInfo.length;i++){
								if(_phraseInfo[i].id==replaceid){
									_phraseInfo[i]=phraseInfo;
								}
							}
						}else{
							_phraseInfo.push(phraseInfo);
						}
						// _this.setState({ phraseInfo: [...this.state.phraseInfo, _phraseInfo],isShowAddDialog: false});//修改当前的值
						_this.setState({isShowAddDialog: false})
						_this.props.saveCallBack() 
			}}
					setVisiable={(val) => {
						_this.setState({ isShowAddDialog: val })
					}}
					controlLayout={jQuery('.wf-req')?jQuery('.wf-req')[0]:null}
				/>}
			</div>
		)
	}
	
	addPhrasesToCKEditor(item){
		const{onAddPhrase}=this.props;
		typeof onAddPhrase === "function"?onAddPhrase(item.workflowPhrasesContent):"";
		this.props.appendHtmlToCKEditor && this.props.appendHtmlToCKEditor(`${item.workflowPhrasesContent}`,'last');
		this.props.showComponent('');
		this.setState({idAdd:false});
		WeaTools.callApi('/api/workflow/userDefaultSetting/updateFrequency', 'POST', {id:item.id,groupid:item.groupid})
	}
	
	doAddPhrase = () => {
		const {newphrase='',phraseInfo} = this.state;
		if(trim(newphrase).length  >  0 && this.realLength(newphrase) <= 30){
			phraseInfo.push({workflowPhrases:newphrase,workflowPhrasesContent:newphrase});
			this.setState({isAdd:false,phraseInfo:phraseInfo,newphrase:''});
			WeaTools.callApi('/api/workflow/reqform/addWfPhrase','POST',{phraseShort:newphrase,phraseDesc:newphrase});
		} else {
            message.warning(getLabel(385870,'文本长度不能超过30(1个中文字符等于3个长度)'), 3);
		}
	}
	
	doChangeEvent = (e) => {
		this.setState({newphrase:e.target.value||''});
	}

    realLength(str){
        let j = 0;
        for(var i = 0; i <= str.length - 1; i++) {
            j = j + 1;
            if((str.charCodeAt(i)) > 127) {
                j = j + 2;
            }
        }
        return j;
    }
}